<template>
    <div class="m-25 mt-65">
        <div class="normal-box-mod">
            <div class="normal-box-hd clearfix">
                <div class="normal-box-title">
                    <div class="decorate-square"></div>
                    <h2>用户管理</h2>
                </div>
            </div>

            <div class="normal-box-bd">
                <div class="clearfix mb-20">
                    <Button custom-icon="iconfont icon-fangkuai2"
                            type="primary"
                            size="small"
                            style="float:right"
                            @click="show_create_user_modal">新建用户</Button>
                    <Input class="mr-10"
                           v-model="search_key_words"
                           placeholder="姓名或账户"
                           style="width: 200px" />
                    <Button type="primary"
                            custom-icon="iconfont icon-chaxun"
                            size="small"
                            @click="get_user_info_by_keywords">搜索</Button>
                </div>

                <div class="mb-20">
                    <Table border
                           :loading="loading_user_list"
                           :columns="user_list_columns"
                           :data="user_list_data"></Table>
                </div>
                <div>
                    <Page :total="data_count"
                          :page-size="limit"
                          :current="current_page"
                          show-total
                          show-elevator
                          @on-change="changepage"></Page>
                </div>

                <!--新建修改用户-->
                <Modal v-model="modals.create_or_update_user_info.show_modal"
                       :title="modals.create_or_update_user_info.modal_title"
                       :loading="modals.create_or_update_user_info.loading"
                       @on-ok="handle_post_user_info">
                    <Form ref="create_or_update_user_info_form"
                          :model="modals.create_or_update_user_info.data"
                          :label-width="80">
                        <FormItem label="姓名"
                                  prop="name"
                                  :rules="modals.create_or_update_user_info.rules.name">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.name"
                                   style="width:400px;" />
                        </FormItem>
                        <FormItem label="帐户"
                                  prop="username"
                                  :rules="modals.create_or_update_user_info.rules.username">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.username"
                                   style="width:400px;" />
                        </FormItem>
                        <!-- <view> -->
                        <!-- <FormItem label="密码" v-if="flag == true"
                                      prop="password"
                                      :rules="modals.create_or_update_user_info.rules.password"
                                      >
                                <Input placeholder="请输入"
                                       v-model="modals.create_or_update_user_info.data.password"
                                       style="width:400px;"
                                        />
                            </FormItem> -->
                        <!-- </view> -->

                        <FormItem label="密码"
                                  v-if="flag == false"
                                  prop="password"
                                  :rules="modals.create_or_update_user_info.rules.password">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.password"
                                   style="width:400px;" />
                        </FormItem>

                        <FormItem label="手机"
                                  prop="mobilePhone"
                                  :rules="modals.create_or_update_user_info.rules.mobilePhone">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.mobilePhone"
                                   style="width:400px;" />
                        </FormItem>
                        <FormItem label="邮箱"
                                  prop="email">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.email"
                                   style="width:400px;" />
                        </FormItem>
                        <FormItem label="描述"
                                  prop="description">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_user_info.data.description"
                                   style="width:400px;" />
                        </FormItem>
                        <FormItem label="地区">
                            <Col span="24"
                                 class="mr-10">
                            <sele @ProvinceData="childByValue"
                                  massage="1"></sele>
                            </Col>
                        </FormItem>
                        <!-- <FormItem label="地区"
                                  v-if="modals.create_or_update_user_info.data.id">
                            <Col span="24"
                                 class="mr-10">
                            <seleNew @ProvinceData="childByValue"
                                     :toChildrenProvincialData='toChildrenProvincialData'></seleNew>
                            </Col>
                        </FormItem> -->
                    </Form>
                </Modal>

                <!--设置管理组-->
                <Modal v-model="modals.set_role_group.show_modal"
                       :title="modals.set_role_group.modal_title"
                       :loading="modals.set_role_group.loading"
                       @on-ok="post_rolegroup_list">
                    <Form ref="set_role_group_form"
                          :rules="modals.set_role_group.rules"
                          :label-width="80">
                        <Tree :data="modals.set_role_group.role_group_tree"
                              show-checkbox
                              multiple></Tree>
                    </Form>
                </Modal>
            </div>
        </div>
    </div>
</template>
<script>
import moment from 'moment'
import sele from '@/view/test/city.vue'
// import seleNew from '@/view/test/cityNewBusiness.vue'

import {
	getUserList,
	createUser,
	putUser,
	delUser,
	getTreeByRoleGroupType,
	ajaxGetUserGroup,
	ajaxPutUserGroup
} from '../../api/base_sys/base_manager'

export default {
	// 引入 注册
	components: {
		sele
		// seleNew,
	},
	data() {
		return {
			loading_user_list: false,
			data_count: 0,
			current_page: 1,
			limit: 10,
			search_key_words: '',
			sex_list: [
				{
					value: '男',
					label: '男'
				},
				{
					value: '女',
					label: '女'
				}
			],
			modals: {
				create_or_update_user_info: {
					show_modal: false,
					is_create: true,
					loading: true,
					modal_title: '新增用户',
					rules: {
						name: [
							{
								required: true,
								message: '请填写姓名',
								trigger: 'blur'
							}
						],
						username: [
							{
								required: true,
								message: '请填写帐户',
								trigger: 'blur'
							}
						],
						password: [
							{
								required: true,
								message: '请填写密码',
								trigger: 'blur'
							},
							{
								type: 'string',
								min: 6,
								message: '密码长度不能小于6位',
								trigger: 'blur'
							}
						],
						mobilePhone: [
							{
								required: true,
								message: '请填写手机号',
								trigger: 'blur'
							}
						],
						description: []
					},
					data: {
						username: '',
						name: '',
						sex: '男',
						password: '123456',
						description: '',
						mail: '',
						mobilePhone: '',
						// 省市区
						provid: '',
						cityid: '',
						distid: '',
						strtid: '',
						commid: '',
						comminid: ''
					}
				},
				set_role_group: {
					show_modal: false,
					loading: true,
					modal_title: '设置角色组',
					userId: null,
					role_group_tree: [], // 权限树
					data: {}
				}
			},
			user_list_columns: [
				{
					title: '序号',
					align: 'center',
					key: 'id',
					minWidth: 80
				},
				{
					title: '姓名',
					align: 'center',
					key: 'name',
					minWidth: 100
				},
				{
					title: '账户',
					align: 'center',
					key: 'username',
					minWidth: 100
				},
				{
					title: '备注',
					align: 'center',
					key: 'description',
					minWidth: 200
				},
				{
					title: '操作',
					align: 'center',
					key: 'name',
					minWidth: 200,
					render: (h, params) => {
						return h('div', [
							//  h(
							//    "Button",
							//    {
							//      props: {
							//        type: "primary",
							//        size: "small",
							//        // icon: "edit"
							//      },
							//      style: {
							//        marginRight: "5px",
							//        padding:"1px 2px"

							//      },
							//      on: {
							//        click: () => {
							//          this.show_update_user_modal(params.index);
							//        }
							//      }
							//    },
							// [h("Icon", { props: { type: "md-create", size: 18} })]
							//  ),
							h(
								'Tooltip',
								{
									props: {
										placement: 'left',
										content: '编辑'
									},
									style: {
										cursor: 'pointer'
									}
								},
								[
									h(
										'Button',
										{
											props: {
												type: 'primary',
												size: 'small'
											},
											style: {
												marginRight: '5px',
												padding: '1px 2px'
											},
											on: {
												click: () => {
													this.show_update_user_modal(
														params.index,
														params.row
													)
												}
											}
										},
										[
											h('Icon', {
												props: {
													type:
														' iconfont icon-bianjisekuai',
													size: 18
												}
											})
										]
									)
								]
							),

							// h(
							//   "Button",
							//   {
							//     props: {
							//       type: "",
							//       size: "small",
							//       // icon: "ios-people"
							//     },
							//     style: {
							//       marginRight: "5px",
							//       padding:"1px 2px"

							//     },
							//     on: {
							//       click: () => {
							//         this.show_set_role_group(params.row.id);
							//       }

							//     }
							//   },
							//  [h("Icon", { props: { type: "md-settings", size: 18} })]
							// ),
							h(
								'Tooltip',
								{
									props: {
										placement: 'right',
										content: '设置'
									},
									style: {
										cursor: 'pointer'
									}
								},
								[
									h(
										'Button',
										{
											props: {
												type: 'success',
												size: 'small'
											},
											style: {
												marginRight: '5px',
												padding: '1px 2px'
											},
											on: {
												click: () => {
													this.show_set_role_group(
														params.row.id
													)
												}
											}
										},
										[
											h('Icon', {
												props: {
													type: 'ios-settings',
													size: 18
												}
											})
										]
									)
								]
							),
							// h(
							//   "Button",
							//   {
							//     props: {
							//       type: "error",
							//       size: "small",
							//       // icon: "trash-a"
							//     },
							//     style: {
							//       marginRight: "5px",
							//       padding:"1px 2px"
							//     },
							//     on: {
							//       click: () => {
							//         this.del_user_confirm(params.index);
							//       }
							//     }
							//   },
							//   [h("Icon", { props: { type: "ios-trash-outline", size: 18 } })]
							// )
							h(
								'Tooltip',
								{
									props: {
										placement: 'right',
										content: '删除'
									},
									style: {
										cursor: 'pointer'
									}
								},
								[
									h(
										'Button',
										{
											props: {
												type: 'error',
												size: 'small'
											},
											style: {
												marginRight: '5px',
												padding: '1px 2px'
											},
											on: {
												click: () => {
													this.del_user_confirm(
														params.index
													)
												}
											}
										},
										[
											h('Icon', {
												props: {
													type:
														' iconfont icon-shanchusekuai',
													size: 18
												}
											})
										]
									)
								]
							)
						])
					}
				}
			],
			user_list_data: [],
			toChildrenProvincialData: [],
			flag: false
		}
	},
	created() {
		this.renderTableList()
	},
	methods: {
		//地区赋值
		childByValue(data) {
			let area = this.modals.create_or_update_user_info.data
			area.provid = data.provid || ''
			area.cityid = data.cityid || ''
			area.distid = data.distid || ''
			area.strtid = data.strtid || ''
			area.commid = data.commid || ''
			area.comminid = data.comminid || ''
		},
		// 获取用户列表数据
		renderTableList() {
			const that = this
			this.loading_user_list = true
			getUserList({
				page: this.current_page,
				limit: this.limit,
				name: this.search_key_words
			}).then(function(rs) {
				if (rs.data) {
					that.user_list_data = rs.data.list
					that.data_count = rs.data.totalRecord
					that.loading_user_list = false
				}
			})
		},
		/**
		 * 切换分页
		 */
		changepage(index) {
			this.current_page = index
			this.renderTableList()
		},
		// 显示新建用户信息弹层
		show_create_user_modal() {
			this.flag = false
			this.$refs['create_or_update_user_info_form'].resetFields()
			this.modals.create_or_update_user_info.show_modal = true
			this.modals.create_or_update_user_info.is_create = true

			this.modals.create_or_update_user_info.data.id = undefined
			this.modals.create_or_update_user_info.modal_title = '添加用户'
			this.modals.create_or_update_user_info.data.username = ''
			this.modals.create_or_update_user_info.data.name = ''
			this.modals.create_or_update_user_info.data.sex = '男'
			this.modals.create_or_update_user_info.data.password = '123456'
			this.modals.create_or_update_user_info.data.description = ''
			this.modals.create_or_update_user_info.data.mobilePhone = ''

			this.modals.create_or_update_user_info.rules.password = [
				{
					required: true,
					message: '请填写密码',
					trigger: 'blur'
				},
				{
					type: 'string',
					min: 6,
					message: '密码长度不能小于6位',
					trigger: 'blur'
				}
			]
		},
		// 显示修改用户信息弹层
		show_update_user_modal(index, row) {
			console.log(row, 'row111111111')
			this.flag = true
			this.modals.create_or_update_user_info.rules.password = []
			this.$refs['create_or_update_user_info_form'].resetFields()
			this.modals.create_or_update_user_info.show_modal = true
			this.modals.create_or_update_user_info.is_create = false
			this.modals.create_or_update_user_info.modal_title = '修改用户'

			// 个人全部数据回显
			this.modals.create_or_update_user_info.data = JSON.parse(
				JSON.stringify(this.user_list_data[index])
			)

			let area = this.modals.create_or_update_user_info.data
			area.provid = ''
			area.cityid = ''
			area.distid = ''
			area.strtid = ''
			area.commid = ''
			area.comminid = ''
			// let provincialData = [
			// 	area.provid,
			// 	area.cityid,
			// 	area.distid,
			// 	area.strtid,
			// 	area.commid,
			// 	area.comminid
			// ]
			// this.toChildrenProvincialData = provincialData.map(Number)
			// this.modals.create_or_update_user_info.data.password = undefined
		},
		// 显示设置用户组弹层
		show_set_role_group(id) {
			this.$refs['set_role_group_form'].resetFields()
			this.modals.set_role_group.show_modal = true
			this.modals.set_role_group.userId = id
			this.get_role_type(id)
		},
		// 渲染用户组树
		renderContent(h, { root, node, data }) {
			return data.label
		},
		// 删除确认
		del_user_confirm(index) {
			const that = this

			const _id = this.user_list_data[index].id
			const _name = this.user_list_data[index].name
			const _username = this.user_list_data[index].username

			this.$Modal.confirm({
				title: '删除确认',
				content:
					'<p>你确认要删除姓名为 <strong>' +
					_name +
					'</strong> ,用户名为 <strong>' +
					_username +
					'</strong> 的记录吗？</p>',
				loading: true,
				onOk: () => {
					delUser(_id)
						.then(function() {
							that.$Modal.remove()
							that.$Message.success('操作成功')
							that.renderTableList()
						})
						.catch(function(e) {
							that.$Message.error('操作失败' + e)
						})
				}
			})
		},
		// 搜索按钮
		get_user_info_by_keywords() {
			this.data_count = 0
			this.current_page = 1
			this.renderTableList()
		},
		// 改变load状态
		change_user_info_loading() {
			this.modals.create_or_update_user_info.loading = false
			this.$nextTick(() => {
				this.modals.create_or_update_user_info.loading = true
			})
		},
		// 提交添加删除用户表单
		handle_post_user_info() {
			this.$refs['create_or_update_user_info_form'].validate(valid => {
				const that = this
				if (!valid) {
					return that.change_user_info_loading()
				}
				if (that.modals.create_or_update_user_info.data.id) {
					// 修改用户
					putUser(that.modals.create_or_update_user_info.data)
						.then(function(rs) {
							that.change_user_info_loading()
							that.modals.create_or_update_user_info.show_modal = false
							that.$Message.success('操作成功')
							that.renderTableList()
						})
						.catch(function(e) {
							that.$Modal.remove()
							that.$Message.error('操作失败' + e)
						})
				} else {
					// 新增用户
					createUser(that.modals.create_or_update_user_info.data)
						.then(function(rs) {
							that.change_user_info_loading()
							that.modals.create_or_update_user_info.show_modal = false
							that.$Message.success('操作成功')
							that.renderTableList()
						})
						.catch(function(e) {
							that.$Modal.remove()
							that.$Message.error('操作失败' + e)
						})
				}
			})
		},
		// 获取角色组
		get_role_type(id) {
			let that = this
			ajaxGetUserGroup(id)
				.then(res => {
					let _tmp_tree_data = res.data
					let access_id_list = []

					that.modals.set_role_group.role_group_tree = that.filter_menu_selected(
						_tmp_tree_data,
						access_id_list
					)
				})
				.catch(function(e) {
					that.$Message.error(e)
				})
		},
		// 获取选中的菜单项
		get_all_selected_rolegroup_id_list(tree_data_list, arr) {
			for (var i = 0; i < tree_data_list.length; i++) {
				if (
					tree_data_list[i]['checked'] === true &&
					tree_data_list[i].children.length == 0
				) {
					arr.push(tree_data_list[i].id)
				}
				if (tree_data_list[i].children.length > 0) {
					this.get_all_selected_rolegroup_id_list(
						tree_data_list[i].children,
						arr
					)
				}
			}
			return arr
		},
		// 处理数据设置是否选中项checked
		filter_menu_selected(origin_data_list, access_list) {
			const arr = []
			for (var i = 0; i < origin_data_list.length; i++) {
				arr[i] = origin_data_list[i]
				arr[i].title = origin_data_list[i].label
				arr[i].checked =
					origin_data_list[i].selected &&
					origin_data_list[i].children.length == 0
						? origin_data_list[i].selected
						: false
				arr[i].selected = undefined

				if (origin_data_list[i].children.length > 0) {
					this.filter_menu_selected(
						origin_data_list[i].children,
						access_list
					)
				}
			}
			return arr
		},
		// 提交角色组权限列表,提交格式为数组形式id
		post_rolegroup_list() {
			const that = this
			const selected_rolegroup_list = this.get_all_selected_rolegroup_id_list(
				this.modals.set_role_group.role_group_tree,
				[]
			)
			ajaxPutUserGroup({
				userId: that.modals.set_role_group.userId,
				groupIds: selected_rolegroup_list
			})
				.then(rs => {
					that.modals.set_role_group.show_modal = false
					that.modals.set_role_group.loading = true
					that.$Message.success('操作成功')
				})
				.catch(error => {
					that.modals.set_role_group.show_modal = false
					that.modals.set_role_group.loading = true
					that.$Message.error(error)
				})
		}
	}
}
</script>
